package com.mantru.iotpot.Cook.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Cook.AdjustFoodActivity;
import com.mantru.iotpot.Cook.CookActivity;
import com.mantru.iotpot.Cook.adapter.FoodDetailsAdapter;
import com.mantru.iotpot.DateClass.CookFood;
import com.mantru.iotpot.DateClass.MaterialData;
import com.mantru.iotpot.DateClass.ingredients;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Tools.ImageLoader;
import com.mantru.iotpot.Tools.LoadingDialogUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class CustomBottomSheetDialogFragment extends BottomSheetDialogFragment implements View.OnClickListener, FoodDetailsAdapter.OnButtonClickListener {
    private String vegetableId;
    private View view;
    private ImageView foodimg;
    private ImageView cencle;
    private TextView textView1;
    private TextView textView2;
    private TextView textView3;
    private TextView textView4;
    private TextView textView5;
    private TextView textView6;
    private ApplicationClass ac;
    private CookFood vegetableList = new CookFood("", "", "", "");
    private List<ingredients> step = new ArrayList<>();
    private TextView foodname;
    private List<MaterialData> materials = new ArrayList<>();
    private FrameLayout cook;
    private String m_sid = "1";
    private String i_sid = "1";
    private FrameLayout t1;
    private String weight;
    private String end_time = "";
    private String num = "";

    // 添加一个方法用于设置vegetableId
    public void setVegetableId(String vegetableId) {
        this.vegetableId = vegetableId;
        Log.d("v_id", "VegetableId: " + vegetableId);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setStyle(STYLE_NORMAL, R.style.BottomSheetDialogTheme);
        view = inflater.inflate(R.layout.activity_food_details, container, false);
        initialization(); // 初始化控件
        Log.d("food", "初始化控件完成");
        ac = (ApplicationClass) getActivity().getApplication(); // 初始化 ApplicationClass
        Log.d("food", "初始化ApplicationClass完成");
        analysis(); // 解析json数据
        Log.d("food", "解析json数据完成");
        ImageLoader.loadImage(vegetableList.getFaceImageUrl(), foodimg); // 使用 ImageLoader 加载图片
        foodname.setText(vegetableList.getVegetableName());
        RecyclerView recyclerView = view.findViewById(R.id.food_details_gridView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        FoodDetailsAdapter adapter = new FoodDetailsAdapter(getContext(), step, this); // 传递接口实现
        recyclerView.setAdapter(adapter);
        star(); // 初步加载控件内容
        cook.setOnClickListener(this);
        cencle.setOnClickListener(this);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(receiver, new IntentFilter("ACTION_CLOSE_LOADING_DIALOG"));
        BottomSheetDialog dialog = (BottomSheetDialog) getDialog();
        if (dialog != null) {
            View bottomSheet = dialog.findViewById(com.google.android.material.R.id.design_bottom_sheet);
            if (bottomSheet != null) {
                // 设置弹窗占满屏幕
                ViewGroup.LayoutParams layoutParams = bottomSheet.getLayoutParams();
                layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; // 将弹窗高度占满屏幕
                bottomSheet.setLayoutParams(layoutParams);
                bottomSheet.setTranslationY(0); // 设置Y坐标为0，确保弹窗从顶部开始显示。
                bottomSheet.setBackgroundResource(android.R.color.transparent);
                // 获取 BottomSheetBehavior 并设置其状态为展开
                BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            }
            // 移除窗口背景（可选）
            View containerView = dialog.getWindow().findViewById(com.google.android.material.R.id.container);
            if (containerView != null) {
                containerView.setBackgroundResource(android.R.color.transparent);
            }
        }

        // 确保在 recycleview 初始化完成后调用 update 方法
        RecyclerView recyclerView = view.findViewById(R.id.food_details_gridView);
        if (recyclerView.getAdapter() != null && recyclerView.getLayoutManager() != null) {
            int firstVisiblePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
            if (firstVisiblePosition != RecyclerView.NO_POSITION && firstVisiblePosition < step.size()) {
                String specId = step.get(firstVisiblePosition).getSpec_id();
                update(specId);
            }
        }
    }

    public void initialization() {
        foodimg = view.findViewById(R.id.food_img);
        cencle = view.findViewById(R.id.food_details_cencle);
        foodname = view.findViewById(R.id.foodname);
        textView1 = view.findViewById(R.id.food_details_test1);
        textView2 = view.findViewById(R.id.food_details_test2);
        textView3 = view.findViewById(R.id.food_details_test3);
        textView4 = view.findViewById(R.id.food_details_test4);
        textView5 = view.findViewById(R.id.food_details_test5);
        textView6 = view.findViewById(R.id.food_details_test6);
        cook = view.findViewById(R.id.food_details_cook);
        t1 = view.findViewById(R.id.food_details_1);
        t1.setOnClickListener(this);
    }

    public void analysis() { // 解析json数据
        materials.clear();
        step.clear();
        if (vegetableId != null) {
            String json_data = ac.GetSQLData_Vegetable_Entity(Integer.parseInt(vegetableId)); // 获取菜单详情
            Log.d("CustomBottomSheetDialogFragment_v_id", "VegetableIdjiexi: " + vegetableId);
            Log.d("CustomBottomSheetDialogFragment_v_json", "json_data: " + json_data);
            try {
                JSONObject jsonObject = new JSONObject(json_data);
                JSONObject dataObject = jsonObject.getJSONObject("data");
                String vegetableId = dataObject.getString("vegetable_id");
                String vegetableName = dataObject.getString("vegetable_name");
                String faceImageUrl = dataObject.getString("face_image_url");
                faceImageUrl = faceImageUrl.replace("file:///", "");
                vegetableList.setVegetableId(vegetableId);
                vegetableList.setVegetableName(vegetableName);
                vegetableList.setFaceImageUrl(faceImageUrl);

                JSONArray specDataArray = dataObject.getJSONArray("spec_data");
                for (int i = 0; i < specDataArray.length(); i++) {
                    JSONObject specDataObject = specDataArray.getJSONObject(i);
                    Log.d("specDataObject", "specDataObject: " + specDataObject);
                    String specId = specDataObject.getString("spec_id");
                    String copiesQty = specDataObject.getString("copies_qty");
                    String weight = specDataObject.getString("weight");
                    String endTime = specDataObject.getString("end_time");
                    Log.d("end_time", "end_time: " + endTime);
                    String creat_time = specDataObject.getString("create_time");
                    step.add(new ingredients(specId, copiesQty, weight, endTime, creat_time));
                    // 继续访问其他字段...
                    // 解析 material_data
                    JSONArray materialDataArray = specDataObject.getJSONArray("material_data");
                    Log.d("getfoodmsg", "materialDataArray" + materialDataArray);
                    Log.d("getfoodmsg", "配料详情信息： " + materialDataArray);
                    for (int j = 0; j < materialDataArray.length(); j++) {
                        JSONObject materialDataObject = materialDataArray.getJSONObject(j);
                        String materialId = materialDataObject.getString("material_id");
                        String boxIndex = materialDataObject.getString("box_index");
                        Log.d("getfoodmsg", "配料料盒信息： " + boxIndex);
                        String materialName = materialDataObject.getString("material_name");
                        Log.d("getfoodmsg", "配料名字信息： " + materialName);
                        String materialWeight = materialDataObject.getString("weight");
                        Log.d("getfoodmsg", "配料重量信息： " + materialWeight);
                        if (materialWeight.equals("0")) {
                            materialWeight = "";
                        }
                        Log.d("getfoodmsg", "配料重量信息： " + materialWeight);
                        String s_id = materialDataObject.getString("spec_id");
                        materials.add(new MaterialData(materialId, vegetableId, s_id, boxIndex, materialName, materialWeight));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("getfoodmsg", "JSON解析失败");
            }
        }
    }

    public void star() { // 初始化配料
        String time = "";
        weight = "";
        for (ingredients ingredients : step) {
            if (i_sid.equals("1")) {
                end_time = ingredients.getEnd_time(); // 获取预估时间
                time = ingredients.getCreate_time(); // 获取创建时间
                num = ingredients.getCopies_qty(); // 获取份数
                weight = ingredients.getWeight(); // 获取重量
            }
        }
        textView5.setText("菜品名称：[" + time + "][" + vegetableList.getVegetableName() + num +
                "份]" + "[" + weight + "克]");
        textView6.setText("预估时长：" + convertTimeFormat(end_time));
        getM_sid(0);
        getI_sid(0);
        // 确保在初始化时调用 update 方法，并传递默认选中项的 specId
        if (!step.isEmpty()) {
            String defaultSpecId = step.get(0).getSpec_id();
            update(defaultSpecId);
        }
    }

    public void onClick(View v) {
        if (v.getId() == R.id.food_details_cook) { // 立即烹饪
            LoadingDialogUtil.showLoadingDialog(getContext()); // 显示加载弹窗
            saveToSharedPreferences();
            Intent intent = new Intent(getActivity(), CookActivity.class);
            intent.putExtra("vegetableId", vegetableId);
            intent.putExtra("sid", i_sid);
            intent.putExtra("quantity", num);
            startActivity(intent);
            dismiss();
        } else if (v.getId() == R.id.food_details_cencle) {
            dismiss();
        } else if (v.getId() == R.id.food_details_1) { // 菜单微调
            LoadingDialogUtil.showLoadingDialog(getContext()); // 显示加载弹窗
            Intent intent = new Intent(getContext(), AdjustFoodActivity.class);
            intent.putExtra("foodname", vegetableList.getVegetableName());
            intent.putExtra("vegetableId", vegetableId);
            intent.putExtra("sid", i_sid);
            intent.putExtra("weight", weight);
//            String copiesQty = "";
//            for (ingredients y : step) {
//                if (i_sid.equals(y.getSpec_id())) {
//                    copiesQty = y.getCopies_qty();
//                }
//            }
            intent.putExtra("copiesQty", num);
            startActivity(intent);
            dismiss();
        }
    }

    public void update(String SID) { // 更新配料
        // 清空界面内容
        textView1.setText("");
        textView2.setText("");
        textView3.setText("");
        textView4.setText("");
        textView5.setText("");
        textView6.setText("");

        // 根据 specId 更新界面内容
        for (MaterialData materialData : materials) {
            if (SID.equals(materialData.getSpec_id())) {
                String boxIndex = materialData.getBox_index();
                String materialName = materialData.getMaterial_name();
                String weight = materialData.getWeight();

                if ("1".equals(boxIndex)) {
                    textView4.setText(materialName + " " + weight + "g");
                } else if ("2".equals(boxIndex)) {
                    textView3.setText(materialName + " " + weight + "g");
                } else if ("3".equals(boxIndex)) {
                    textView2.setText(materialName + " " + weight + "g");
                } else if ("4".equals(boxIndex)) {
                    textView1.setText(materialName + " " + weight + "g");
                }
            }
        }

        // 更新其他界面内容
        for (ingredients ingredients : step) {
            if (SID.equals(ingredients.getSpec_id())) {
                end_time = ingredients.getEnd_time();
                String time = ingredients.getCreate_time();
                num = ingredients.getCopies_qty();
                weight = ingredients.getWeight();
                i_sid = ingredients.getSpec_id();

                textView5.setText("菜品名称：[" + time + "][" + vegetableList.getVegetableName() + num +
                        "份]" + "[" + weight + "克]");
                textView6.setText("预估时长：" + convertTimeFormat(end_time));
            }
        }
    }

    // 获取菜谱详情id（X份Yg）
    public void getM_sid(int n) {
        if (!materials.isEmpty()) { // 确保列表不为空
            MaterialData firstMaterial = materials.get(n); // 获取第一个元素
            m_sid = firstMaterial.getSpec_id();
        }
    }

    public void getI_sid(int n) {
        if (!step.isEmpty()) {
            ingredients firstingredients = step.get(n);
            i_sid = firstingredients.getSpec_id();
        }
    }

    public static String convertTimeFormat(String timeString) {
        try {
            // 将传入的秒数字符串转换为整数
            int totalSeconds = Integer.parseInt(timeString);
            // 计算分钟和秒
            int minutes = totalSeconds / 60;
            int seconds = totalSeconds % 60;

            // 根据不同的情况返回不同的格式
            if (minutes == 0 && seconds == 0) {
                return "0秒";
            } else if (minutes == 0) {
                return seconds + "秒";
            } else if (seconds == 0) {
                return minutes + "分钟";
            } else {
                return minutes + "分钟" + seconds + "秒";
            }
        } catch (NumberFormatException e) {
            // 捕获转换异常
            return "格式错误";
        }
    }

    @Override
    public void onButtonClick(String specId) {
        // 处理按钮点击事件，获取 specId
        update(specId);
        Log.d("gridview", "specId: " + specId);
    }

    // 将菜品的信息保存到本地
    private void saveToSharedPreferences() {
        // 获取 SharedPreferences
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("CookPreferences", Context.MODE_PRIVATE);
        // 获取编辑器
        SharedPreferences.Editor editor = sharedPreferences.edit();
        // 保存 num 、 end_time 和 食物名
        editor.putString("food_num", num);
        editor.putString("end_time", convertTimeFormat(end_time));
        editor.putString("food_name", vegetableList.getVegetableName());
        editor.putString("food_img", vegetableList.getFaceImageUrl());
        // 提交保存
        editor.apply();
        Log.d("food", "保存到 SharedPreferences: num=" + num + ", end_time=" + convertTimeFormat(end_time)
                + ", food_name=" + vegetableList.getVegetableName() + ", food_img=" + vegetableList.getFaceImageUrl());
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("ACTION_CLOSE_LOADING_DIALOG".equals(intent.getAction())) {
                LoadingDialogUtil.closeLoadingDialog();
            }
        }
    };


    @Override
    public void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(receiver);
    }
}